package c

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/community/request"
	"github.com/flipped-aurora/gin-vue-admin/server/service/system"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// CommunityApi 社区相关接口
type CommunityApi struct{}

// GetCommunityDetail
// @Tags      C端用户
// @Summary   获取社区详情
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     communityId  query     int64  false  "社区ID"
// @Param     majorId      query     int    false  "专业ID"
// @Success   200          {object}  response.Response{data=community.Community,msg=string}  "获取社区详情成功"
// @Router    /community/getCommunityDetail [get]
func (b *CommunityApi) GetCommunityDetail(c *gin.Context) {
	// 获取查询参数
	communityIdStr := c.Query("communityId")
	majorIdStr := c.Query("majorId")

	// 调用服务层方法获取社区详情
	community, err := communityService.GetCommunityDetail(communityIdStr, majorIdStr)
	if err != nil {
		global.GVA_LOG.Error("获取社区详情失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(community, c)
}

// GetCommunityList
// @Tags      C端用户
// @Summary   获取社区列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.CommunityListRequest  true  "页码, 每页大小, 搜索条件"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "获取社区列表成功"
// @Router    /community/getCommunityList [post]
func (b *CommunityApi) GetCommunityList(c *gin.Context) {
	var pageInfo request.CommunityListRequest
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	list, total, err := communityService.GetCommunityList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取社区列表失败!", zap.Error(err))
		response.FailWithMessage("获取社区列表失败", c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// JoinCommunity
// @Tags      C端用户
// @Summary   加入社区
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200   {object}  response.Response{msg=string}  "加入社区成功"
// @Router    /community/joinCommunity [post]
func (b *CommunityApi) JoinCommunity(c *gin.Context) {
	// 1. 获取当前用户ID
	userId := utils.GetUserID(c)

	// 2. 检查用户是否已完成专业认证
	isAuth, err := system.UserServiceApp.CheckUserMajorAuthStatus(userId)
	if err != nil {
		global.GVA_LOG.Error("检查用户专业认证状态失败!", zap.Error(err))
		response.FailWithMessage("系统错误，请稍后重试", c)
		return
	}

	if !isAuth {
		// 未认证则拦截
		response.FailWithMessage("请先完成专业认证", c)
		return
	}

	// 3. 获取用户信息，获取专业ID
	user, err := system.UserServiceApp.GetUserByID(userId)
	if err != nil {
		global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
		response.FailWithMessage("系统错误，请稍后重试", c)
		return
	}

	if user.Major == 0 {
		response.FailWithMessage("您的专业信息未完善", c)
		return
	}

	// 4. 根据用户的专业ID获取对应的社区
	communityInfo, err := communityService.GetCommunityByMajorID(user.Major)
	if err != nil {
		global.GVA_LOG.Error("获取专业对应的社区失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 5. 调用服务层方法加入社区
	err = communityService.JoinCommunity(userId, communityInfo.ID)
	if err != nil {
		global.GVA_LOG.Error("加入社区失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("加入社区成功", c)
}

// LeaveCommunity
// @Tags      C端用户
// @Summary   离开社区
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.LeaveCommunityRequest  true  "社区ID"
// @Success   200   {object}  response.Response{msg=string}  "离开社区成功"
// @Router    /community/leaveCommunity [post]
func (b *CommunityApi) LeaveCommunity(c *gin.Context) {
	var req request.LeaveCommunityRequest
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(req, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	userId := utils.GetUserID(c)
	err = communityService.LeaveCommunity(userId, req.CommunityID)
	if err != nil {
		global.GVA_LOG.Error("离开社区失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("离开社区成功", c)
}

// GetMajorCategoriesWithCommunity
// @Tags      C端用户
// @Summary   获取专业大类及对应社区id
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=[]map[string]interface{},msg=string}  "获取专业大类及对应社区id成功"
// @Router    /community/getMajorCategoriesWithCommunity [get]
func (b *CommunityApi) GetMajorCategoriesWithCommunity(c *gin.Context) {
	// 调用服务层方法获取专业大类及对应社区id
	result, err := communityService.GetMajorCategoriesWithCommunity()
	if err != nil {
		global.GVA_LOG.Error("获取专业大类及对应社区id失败!", zap.Error(err))
		response.FailWithMessage("获取专业大类及对应社区id失败", c)
		return
	}

	response.OkWithDetailed(result, "获取专业大类及对应社区id成功", c)
}

// ValidateCommunityMajorRelation
// @Tags      社区管理
// @Summary   校验社区与专业关系
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{msg=string}  "校验成功"
// @Router    /community/validateCommunityMajorRelation [post]
func (b *CommunityApi) ValidateCommunityMajorRelation(c *gin.Context) {
	err := communityService.ValidateCommunityMajorRelation()
	if err != nil {
		global.GVA_LOG.Error("校验社区与专业关系失败!", zap.Error(err))
		response.FailWithMessage("校验失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("校验成功", c)
}

// GetCommunityTree
// @Tags      C端用户
// @Summary   获取社区二层树结构
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Success   200  {object}  response.Response{data=[]CommunityTreeNode,msg=string}  "获取社区二层树结构成功"
// @Router    /community/getCommunityTree [get]
func (b *CommunityApi) GetCommunityTree(c *gin.Context) {
	// 调用服务层方法获取社区二层树结构
	communityTree, err := communityService.GetCommunityTree(c)
	if err != nil {
		global.GVA_LOG.Error("获取社区二层树结构失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(communityTree, c)
}

// GetSimpleCommunityTree 获取简化的社区二层树结构
// @Tags Community
// @Summary 获取简化的社区二层树结构
// @Description 获取包含1层13大类虚拟社区和2层关联物理社区的树形结构，每个社区只返回必要信息
// @Accept json
// @Produce json
// @Success 200 {object} response.Response{data=[]response.SimpleCommunityTreeNode,msg=string}
// @Router /c/community/simple_tree [get]
func (communityApi *CommunityApi) GetSimpleCommunityTree(c *gin.Context) {
	// 调用Service层方法获取简化社区树
	tree, err := communityService.GetSimpleCommunityTree(c)
	if err != nil {
		response.FailWithMessage("获取社区树失败", c)
		return
	}
	response.OkWithDetailed(tree, "获取社区树成功", c)
}
